import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, message } from 'antd'
import ReactECharts from 'echarts-for-react'
import moment from 'moment';
import { removeCookies } from '../../utils/storage'
import { get } from '../../api/axios'
import './style.css'

interface CourseItem {
  title: string
  count: number
}

interface State {
  loading: boolean
  data: {
    [key: string]: CourseItem[]
  }
}

const Home = () => {
  const navigate = useNavigate()

  const [state, setData] = useState<State>({
    loading: false,
    data: {}
  })
  const getData = () => {
    get('/api/getData', {}).then((res) => {
      if (res.data) {
        message.success('爬虫成功')
      }
    })
  }
  const showData = () => {
    get('/api/showData', {}).then((res) => {
      if (res.data) {
        setData({ data: res.data, loading: true })
      }
    })
  }

  useEffect(() => {
    showData()
  }, [])

  const logout = () => {
    removeCookies('session')
    navigate('/login')
    message.success('退出成功')
  }

  const getOption: () => echarts.EChartsOption = () => {
    const { data } = state
    const courseNames: string[] = []
    const times: string[] = []
    const tempData: {
      [key: string]: number[];
    } = {};
    for (let i in data) {
      const item = data[i]
      times.push(moment(Number(i)).format('MM-DD HH:mm'));
      item.forEach((innerItem) => {
        const { title, count } = innerItem
        if (courseNames.indexOf(title) === -1) {
          courseNames.push(title)
        }
        tempData[title] ? tempData[title].push(count) : (tempData[title] = [count])
      })
    }
    console.log('data--->', courseNames) // SeriesOption$1
    const result: echarts.SeriesOption[] = [];
    for (let i in tempData) {
      result.push({
        name: i,
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: tempData[i]
      });
    }
    return {
      title: {
        text: '课程在线学习人数'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985'
          }
        }
      },
      legend: {
        data: courseNames
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          boundaryGap: false,
          data: times
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: result
    }
  }

  return (
    <div className="home-page">
      <div className="btns">
        <Button type="primary" onClick={getData}>
          爬虫
        </Button>
        <Button type="primary" onClick={logout}>
          退出
        </Button>
      </div>
      {state.loading && <ReactECharts option={getOption()} />}
    </div>
  )
}

export default Home
